package com.appspot.yozmcup;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oauth.signpost.OAuthConsumer;

import com.appspot.yozmcup.DAO.YozmDAO;
import com.appspot.yozmcup.DO.User;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class JoinYozmServlet extends HttpServlet {
	private static final long serialVersionUID = -3351078179953447907L;

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
		User user = null;
		HttpSession session = req.getSession();
		String paramNickname = req.getParameter("nickname");
		String paramSex = req.getParameter("sex");
		String paramBirthday= req.getParameter("birthday");
		String paramBloodType = req.getParameter("bloodType");
		RequestDispatcher rd = null;
		if(paramNickname != null){
			OAuthConsumer consumer = (OAuthConsumer) session.getAttribute("consumer");
			JSONObject result = YozmDAO.joinYozmObject(consumer, paramNickname, paramSex, paramBirthday, paramBloodType);
			try {
				if(result.getInt("status")==200 && user != null){
					JSONObject myinfoJson = YozmDAO.getMyInfoObject(consumer);
					String myinfoStr = YozmDAO.getMyInfo(consumer);
					req.setAttribute("myinfoStr", myinfoStr);
					JSONObject jsonUser = myinfoJson.getJSONObject("user");
		        
			        String urlName = jsonUser.getString("url_name");
			        String sexCode = jsonUser.getString("sex_code");
			        String nickname = jsonUser.getString("nickname");
			        
					user = new User(urlName, nickname, sexCode);
			        
			        session.setAttribute("user", user);
					rd = getServletContext().getRequestDispatcher("/member.jsp");
				}else{
					req.setAttribute("msg", result.getString("result_msg"));
					rd = getServletContext().getRequestDispatcher("/error.jsp");
				}
			} catch (JSONException e) {
				e.printStackTrace();
				req.setAttribute("msg", "에러가 발생했습니다.");
				rd = getServletContext().getRequestDispatcher("/error.jsp");
			}
		}else{
			req.setAttribute("msg", "닉네임은 필수항목입니다.");
			rd = getServletContext().getRequestDispatcher("/error.jsp");
		}
		
		try {
			rd.forward(req, res);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
